// Cache name and version
const CACHE_NAME = "bhhs-cache-v1";

// Only cache HTTP/HTTPS requests
self.addEventListener("fetch", event => {
  // Skip non-http/https requests (including chrome-extension)
  if (!event.request.url.startsWith("http")) {
    return;
  }
  
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        if (response) {
          return response;
        }
        
        return fetch(event.request)
          .then(networkResponse => {
            if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== "basic") {
              return networkResponse;
            }
            
            const responseToCache = networkResponse.clone();
            
            // Safely handle caching
            caches.open(CACHE_NAME)
              .then(cache => {
                try {
                  if (event.request.url.startsWith("http")) {
                    cache.put(event.request, responseToCache);
                  }
                } catch (error) {
                  console.error("Cache error:", error);
                }
              });
            
            return networkResponse;
          });
      })
  );
}); 